
package view;

import controllers.LoginServiceControl;
import java.util.ConcurrentModificationException;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import net.sf.jasperreports.engine.type.EvaluationTimeEnum;
import ws.login.Exception_Exception;
import ws.login.NormalizedEstablishment;

public class LoginDialog extends CustomizedStage {
    
    private GridPane grid;
    private TextField usernameTF;
    private PasswordField passwordPF;
    private Button loginB;
    private Button cancelB;
    private Button contactB;
    private Tooltip emptyUsernameT;
    private Tooltip emptyPasswordT;
    private Tooltip noUserT;
    private Label mainL;
    private Label usernameL;
    private Label passwordL;
    
    private LoginServiceControl loginControl = new LoginServiceControl();

    public LoginDialog(Stage owner) {
        this(owner, 0, 0);
    }

    public LoginDialog(Stage owner, double width, double height) {
        super(owner, "Login", width, height);
        grid=new GridPane();
        grid.setPadding(new Insets(20));
        grid.setHgap(10);
        grid.setVgap(6);
        mainL=new Label("Ingrese nombre de usuario y contraseña");
        GridPane.setMargin(mainL, new Insets(0, 0, 5, 0));
        usernameL=new Label("Usuario");
        usernameL.setTooltip(new Tooltip("Es el nombre de usuario asociado a la sucursal desde la cual esta accediendo"));
        passwordL=new Label("Contraseña");
        usernameTF=new TextField();
        passwordPF=new PasswordField();
        loginB=new Button("Aceptar");
        loginB.setOnAction(loginAction(this));
        cancelB=new Button("Cancelar");
        cancelB.setTooltip(new Tooltip("Si no inicia sesión no podra continuar"));
        cancelB.setOnAction(cancelAction());
        HBox buttonsHBox=new HBox(7);
        GridPane.setHalignment(buttonsHBox, HPos.RIGHT);
        GridPane.setMargin(buttonsHBox, new Insets(2, 0, 0, 0));
        buttonsHBox.getChildren().addAll(loginB,cancelB);
        Separator afterButtonsSeparator=new Separator();
        GridPane.setMargin(afterButtonsSeparator, new Insets(3, 0, 3, 0));
        contactB=new Button("¿Problemas para conectarse?");
        contactB.setOnAction(contactAction());
        GridPane.setHalignment(contactB, HPos.RIGHT);
        initTooltips();
        usernameTF.setOnKeyReleased(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent event) {
                if(emptyUsernameT.isShowing())
                    emptyUsernameT.hide();
                if(event.getCode().toString().equals("ENTER")){
                    passwordPF.requestFocus();
                    passwordPF.selectAll();
                }
            }
        });
        usernameTF.setOnKeyTyped(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent event) {
                if(emptyUsernameT.isShowing())
                    emptyUsernameT.hide();
            }
        });
        passwordPF.setOnKeyTyped(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent event) {
                if(emptyPasswordT.isShowing())
                    emptyPasswordT.hide();
                if(noUserT.isShowing())
                    noUserT.hide();
            }
        });
        passwordPF.setOnKeyReleased(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent event) {
                if(event.getCode().toString().equals("ENTER")){
                    try{
                        loginB.fire();
                    }catch(ConcurrentModificationException ignore){
                    }
                }
            }
        });
        grid.add(mainL, 0, 0, 2, 1);
        grid.add(usernameL, 0, 1);
        grid.add(passwordL, 0, 2);
        grid.add(usernameTF, 1, 1);
        grid.add(passwordPF, 1, 2);
        grid.add(buttonsHBox, 1, 3);
        grid.add(afterButtonsSeparator,0,4,2,1);
        grid.add(contactB, 1, 5);
        setContent(grid);
        setOnCloseRequest(new EventHandler<WindowEvent>() {
            @Override
            public void handle(WindowEvent t) {
                Platform.exit();
                System.exit(0);
            }
        });
    }
    
    /**
     * 
     */
    public void showStage(){
        show();
        usernameTF.requestFocus();
    }
    
    /**
     * 
     */
    private void initTooltips(){
       emptyUsernameT=TooltipBuilder.create()
            .text("Inserte el nombre de usuario")
            .hideOnEscape(true)
            .autoHide(true)
            .build();
       emptyPasswordT=TooltipBuilder.create()
            .text("Inserte la contraseña")
            .hideOnEscape(true)
            .autoHide(true)
            .build();
       noUserT=TooltipBuilder.create()
            .text("Usuario o contraseña incorrecta")
            .hideOnEscape(true)
            .autoHide(true)
            .build();
    }

    /**
     * 
     * @return 
     */
    private EventHandler<ActionEvent> loginAction(final Stage stage){
        return new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                boolean tryLogin=true;
                TextField empty=null;
                if (usernameTF.getText().toString().equals("")){
                    emptyUsernameT.show(usernameTF, 
                        stage.getX()+usernameTF.getLayoutX()+usernameTF.getWidth(),
                        stage.getY()+usernameTF.getLayoutY()+usernameTF.getHeight()-5);
                    tryLogin=false;
                    empty=usernameTF;
                }
                if (passwordPF.getText().toString().equals("")){
                    emptyPasswordT.show(passwordPF, 
                        stage.getX()+passwordPF.getLayoutX()+passwordPF.getWidth(),
                        stage.getY()+passwordPF.getLayoutY()+passwordPF.getHeight()-5);
                    tryLogin=false;
                    if(empty==null)
                        empty=passwordPF;
                }
                if(tryLogin){
                    NormalizedEstablishment branch;
                    try {
                        branch = loginControl.loginEstablishment(usernameTF.getText(), passwordPF.getText());
                    } catch (Exception_Exception ex) {
                        branch = null;
                    }
                    if (branch == null){
                        noUserT.show(contactB, 
                            stage.getX()+contactB.getLayoutX(),
                            stage.getY()+contactB.getLayoutY());
                        usernameTF.requestFocus();
                        usernameTF.selectAll();
                    }else{
                        MainWindow.setActiveUser(branch);
                        if (branch.getStatus().equals("no_upload")){
                            MainWindow.changeMenuItemsState(false);
                        }
                        stage.close();
                        MainWindow.showLoadPane();
                    }
                }else
                    empty.requestFocus();
            }
        };
    }
    
    /**
     * 
     */
    protected void closeDialog(){
        emptyUsernameT.hide();
        emptyPasswordT.hide();
        noUserT.hide();
        close();
    }
    
    /**
     * 
     * @return 
     */
    private EventHandler<ActionEvent> cancelAction(){
        return new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                System.out.println("Terminando...");
                Platform.exit();
            }
        };
    }
    
    /**
     * 
     * @return 
     */
    private EventHandler<ActionEvent> contactAction(){
        return new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                MainWindow.closeLoginDialog();
                MainWindow.showLoginContactDialog();
            }
        };
    }    
}